package com.wkbb.sports.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wkbb.common.base.BaseServiceImpl;
import com.wkbb.common.constants.ErrorCode;
import com.wkbb.common.dto.ResultDTO;
import com.wkbb.common.dto.basic.GradeDto;
import com.wkbb.common.utils.TimeUtil;
import com.wkbb.sports.dto.ExamineDto;
import com.wkbb.sports.dto.PhysicalDto;
import com.wkbb.sports.dto.TermDto;
import com.wkbb.sports.mapper.HlifeExamineMapper;
import com.wkbb.sports.mapper.HlifePhysicalMapper;
import com.wkbb.sports.mapper.HlifeTermMapper;
import com.wkbb.sports.model.HlifeExamine;
import com.wkbb.sports.model.HlifePhysical;
import com.wkbb.sports.model.HlifeTerm;
import com.wkbb.sports.service.TermService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class TermServiceImpl extends BaseServiceImpl<HlifeTerm> implements TermService {

    @Autowired
    private HlifeTermMapper termMapper;

    @Autowired
    private HlifeExamineMapper examineMapper;

    @Autowired
    private HlifePhysicalMapper physicalMapper;
    /**
     * 分页查询
     * @param params
     * @param pageNo
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<TermDto> getTermPageList(Map<String, Object> params, Integer pageNo, Integer pageSize) {
        if (pageNo == null || pageSize == null) {
            return null;
        }
        Page<ExamineDto> page = PageHelper.startPage(pageNo, pageSize, true);
        PageInfo<TermDto> pageInfo = new PageInfo<TermDto>(termMapper.getTermPageList(params));
        pageInfo.setTotal(page.getTotal());
        return pageInfo;
    }

    /**
     * 新增考试项目
     * @param termDto
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResultDTO addTerm(TermDto termDto) {
        if (termDto.getName().length() > 30){
            return new ResultDTO(ErrorCode.BUSINESS_DATA_WRONG);
        }
        long beginTime = termDto.getDateBegin().getTime();  //开始时间
        long endTime = termDto.getDateEnd().getTime();      //结束时间
        //开始时间不能小于结束的时间
        if (beginTime >= endTime){
                return new ResultDTO(ErrorCode.BUSINESS_DATA_WRONG);
        }
        JSONObject projectInfo = new JSONObject();      //项目信息
        HlifeTerm hlifeTerm = new HlifeTerm();
        hlifeTerm.setDateBegin(termDto.getDateBegin());         //开始时间
        hlifeTerm.setDateEnd(termDto.getDateEnd());             //结束时间
        hlifeTerm.setState((byte)0);                            //考试状态
        hlifeTerm.setType(termDto.getType());                   //考试类型
        hlifeTerm.setStatus((byte)1);                           //是否有效
        hlifeTerm.setOrgId(termDto.getOrgId());                 //学校id
        hlifeTerm.setName(termDto.getName());                   //考试名称
        JSONArray gradeArray = new JSONArray();                 //年级数组
        JSONArray examineArray = new JSONArray();
        JSONArray physicalArray = new JSONArray();
        for (GradeDto gradeDto : termDto.getGradeDtos()) {
            JSONObject gradeObj = new JSONObject();         //年级信息
            gradeObj.put("gradeId",gradeDto.getId());
            gradeObj.put("gradeName",gradeDto.getGradeName());
            gradeArray.add(gradeObj);
            hlifeTerm.setGradeInfo(gradeArray);
        }

        for (PhysicalDto physicalDto : termDto.getPhysicalDtos()) {
            JSONObject physicalObj = new JSONObject();          //体质
            physicalObj.put("id",physicalDto.getId());
            physicalObj.put("name",physicalDto.getName());
            physicalArray.add(physicalObj);
        }
        projectInfo.put("physical",physicalArray);
        for (ExamineDto examineDto : termDto.getExamineDtos()) {
            JSONObject examineObj = new JSONObject();                   //体检
            examineObj.put("id",examineDto.getId());
            examineObj.put("name",examineDto.getName());
            examineArray.add(examineObj);
        }
        projectInfo.put("examine",examineArray);
        hlifeTerm.setProjectInfo(projectInfo);
        termMapper.insert(hlifeTerm);
        return new ResultDTO(true);
    }

    /**
     * 修改考试信息
     * @param termDto
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResultDTO updateTerm(TermDto termDto) {
        Map<String,Object> params = new HashMap<>();
        params.put("orgId",termDto.getOrgId());
        params.put("id",termDto.getId());
        HlifeTerm term = termMapper.getByMapParams(params);
        if (termDto.getId().longValue() ==term.getId().longValue()){
            long beginTime = termDto.getDateBegin().getTime();  //开始时间
            long endTime = termDto.getDateEnd().getTime();      //结束时间
            //开始时间不能小于结束的时间
            if (beginTime >= endTime){
                return new ResultDTO(ErrorCode.BUSINESS_DATA_WRONG);
            }
            //考试进行中,只可以修改名字
            if(term.getState() == 1){
                HlifeTerm hlifeTerm = new HlifeTerm();
                hlifeTerm.setName(termDto.getName());
                hlifeTerm.setId(termDto.getId());
                termMapper.update(hlifeTerm);
                return new ResultDTO(true);
            }
            //考试类型obj
            JSONObject projectInfo = new JSONObject();
            HlifeTerm hlifeTerm = new HlifeTerm();
            hlifeTerm.setName(termDto.getName());
            hlifeTerm.setId(termDto.getId());
            hlifeTerm.setType(termDto.getType());
            hlifeTerm.setOrgId(termDto.getOrgId());
            hlifeTerm.setDateBegin(termDto.getDateBegin());
            hlifeTerm.setDateEnd(term.getDateEnd());
            JSONArray gradeArray = new JSONArray();                 //年级数组
            JSONArray examineArray = new JSONArray();
            JSONArray physicalArray = new JSONArray();
            for (GradeDto gradeDto : termDto.getGradeDtos()) {
                JSONObject gradeObj = new JSONObject();         //年级信息
                gradeObj.put("gradeId",gradeDto.getId());
                gradeObj.put("gradeName",gradeDto.getGradeName());
                gradeArray.add(gradeObj);
                hlifeTerm.setGradeInfo(gradeArray);
            }
            for (PhysicalDto physicalDto : termDto.getPhysicalDtos()) {
                JSONObject physicalObj = new JSONObject();          //体质
                physicalObj.put("id",physicalDto.getId());
                physicalObj.put("name",physicalDto.getName());
                physicalArray.add(physicalObj);
            }
            projectInfo.put("physical",physicalArray);
            for (ExamineDto examineDto : termDto.getExamineDtos()) {
                JSONObject examineObj = new JSONObject();                   //体检
                examineObj.put("id",examineDto.getId());
                examineObj.put("name",examineDto.getName());
                examineArray.add(examineObj);
            }
            projectInfo.put("examine",examineArray);
            hlifeTerm.setProjectInfo(projectInfo);
            termMapper.update(hlifeTerm);
        }else {
            return new ResultDTO(ErrorCode.AREA_TEMPLATE_EXIST);
        }
        return new ResultDTO(true);
    }

    /**
     * 删除考试项目
     * @param orgId
     * @param termId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResultDTO delTerm(Long orgId,Long termId) {
        Map<String,Object> params = new HashMap<>();
        params.put("orgId",orgId);
        params.put("id",termId);
        Date date = new Date();
        String currentTime = TimeUtil.toString(date, "yyyy-MM-dd HH:mm:ss");
        params.put("termTime",currentTime);
        //查询当前考试项目是否正在进行
        HlifeTerm term = termMapper.getByMapParams(params);
        if (term != null){
            return new ResultDTO(false,"200","当前考试科目正在进行中,不能进行删除");
        }
        HlifeTerm hlifeTerm = new HlifeTerm();
        hlifeTerm.setOrgId(orgId);
        hlifeTerm.setId(termId);
        termMapper.delTerm(hlifeTerm);
        return new ResultDTO(true);
    }

    /**
     * 获取考试项目类型列表
     * @param orgId
     * @return
     */
    @Override
    public List<TermDto> getTermType(Long orgId) {
        //体质体检项目名称列表
        List<TermDto> termList = new ArrayList<>();
        List<ExamineDto> examineDtoList = new ArrayList<>();
        List<PhysicalDto> physicalDtoList = new ArrayList<>();
        TermDto term = new TermDto();
        Map<String,Object> params = new HashMap<>();
        params.put("orgId",orgId);
        //体检项目名称列表
        List<HlifeExamine> examineList = examineMapper.getListByMapParams(params);
        //List<HlifePhysical> physicalList = physicalMapper.getListByMapParams(params);
        physicalDtoList = physicalMapper.queryPhysicalListByOrg(orgId, null, null);
        //封装体检项目列表
        for (HlifeExamine hlifeExamine : examineList) {
            ExamineDto examineDto = new ExamineDto();
            examineDto.setId(hlifeExamine.getId());
            examineDto.setName(hlifeExamine.getName());
            examineDtoList.add(examineDto);
        }
        //封装体质项目列表
       /* for (HlifePhysical hlifePhysical : physicalList) {
            PhysicalDto physicalDto = new PhysicalDto();
            physicalDto.setId(hlifePhysical.getId());
            physicalDto.setName(hlifePhysical.getName());
            physicalDtoList.add(physicalDto);
        }*/
        term.setExamineDtos(examineDtoList);                //体检项目列表
        term.setPhysicalDtos(physicalDtoList);              //体质项目列表
        termList.add(term);
        return termList;
    }


    /**
     * 考试信息详情
     * @param params
     * @return
     */
    @Override
    public ResultDTO getTerm(Map<String, Object> params) {
        TermDto termDto = termMapper.getTrem(params);
        return new ResultDTO(termDto);
    }

    @Override
    public void updateTermStatus()
    {
        termMapper.updateTermBegin();
        termMapper.updateTermEnd();
    }
}
